package com.ciwong.epaper.modules.pigai.ui;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.OcrRequestParams;
import com.baidu.ocr.sdk.model.OcrResponseResult;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.pigai.util.PigaiJumpManager;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.ViewUtil;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.utils.fileprovider.FileProvider7;
import com.ciwong.mobilelib.widget.BottomMenuDialog;
import com.ciwong.mobilelib.widget.CWDialog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作文批改
 *
 * @author paul
 * @version ciwong v.1.0 2024/11/14 09:10
 * @since ciwong v.1.0
 */
public class PigaiStartActivity extends BaseActivity implements View.OnClickListener {
    /**
     * 跳转码，拍照
     */
    public static final int REQUEST_CODE_CAMERA = 0x0000011;

    /**
     * 跳转码，相册
     */
    public static final int REQUEST_CODE_ALBUM = 0x0000012;

    /**
     * 跳转码，拍照裁剪图片
     */
    public static final int REQUEST_CODE_CROP_CAMERA = 0x0000013;

    /**
     * 跳转码，相册裁剪图片
     */
    public static final int REQUEST_CODE_CROP_ALBUM = 0x0000014;

    /**
     * 跳转码，识别结果
     */
    public static final int REQUEST_CODE_WRITTEN_RESULT = 0x0000015;

    /**
     * 跳转码，切换学校
     */
    public static final int REQUEST_CODE_SCHOOL = 0x0000016;

    /**
     * 跳转码，修改性名
     */
    public static final int REQUEST_CODE_UPDATE_USERNAME = 0x0000017;

    private EApplication application;

    private Uri photoUri;

    private File tempFile;

    private BottomMenuDialog bottomMenuDialog;

    private CWDialog getSDcardPermissDialog;
    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    private LinearLayout ll_take_phote_pigai;

    class BottomClickListener extends ViewOnClickListener {
        private int index;

        public BottomClickListener(int index) {
            this.index = index;
        }

        @Override
        public void avertRepeatOnClick(View v) {
            switch (index) {
                case 0:// 拍照
                    showgetCameraPermissDialog();
                    break;
                case 1:// 从相册选
                    showgetAlbumPermissDialog();
                    break;
                default:
                    break;
            }
            bottomMenuDialog.dismiss();
        }
    }

    private final int CODE_REQUEST_ALBUM_PERMISSION = 9900;
    private final int CODE_REQUEST_CAMERA_PERMISSION = 9901;
    private CWDialog getAlbumPermissDialog;

    /**
     * 获取Album权限提示框
     */
    private boolean showgetAlbumPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            useAlbum();
        } else {
            if (getAlbumPermissDialog == null) {
                getAlbumPermissDialog = new CWDialog(this);
                getAlbumPermissDialog.setTitle(R.string.get_permiss_title);
                getAlbumPermissDialog.setTitleTextColor(Color.BLACK);
                getAlbumPermissDialog.setMessage(getString(R.string.get_album_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getAlbumPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                        useAlbum();
                    }
                });
                getAlbumPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                    }
                });
            }
            getAlbumPermissDialog.show();
        }
        return true;
    }

    private CWDialog getCameraPermissDialog;

    /**
     * 获取Camera权限提示框
     */
    private boolean showgetCameraPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.CAMERA);
        if (isHavePermiss) {
            useCamera();
        } else {
            if (getCameraPermissDialog == null) {
                getCameraPermissDialog = new CWDialog(this);
                getCameraPermissDialog.setTitle(R.string.get_permiss_title);
                getCameraPermissDialog.setTitleTextColor(Color.BLACK);
                getCameraPermissDialog.setMessage(getString(R.string.get_camera_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getCameraPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                        useCamera();
                    }
                });
                getCameraPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                    }
                });
            }
            getCameraPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用相册，判断权限
     */
    private void useAlbum() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_ALBUM_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                BaseJumpManager.jumpToSysAlbum(PigaiStartActivity.this,
                                        REQUEST_CODE_ALBUM);
                            }
                        }
                    });
        } else {
            BaseJumpManager.jumpToSysAlbum(PigaiStartActivity.this,
                    REQUEST_CODE_ALBUM);
        }
    }

    /**
     * 使用照相机，判断权限
     */
    private void useCamera() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList_camera = new ArrayList<String>();
            Map<String, String> noteMap_camera = new HashMap<>();
            noteMap_camera.put(Manifest.permission.CAMERA, "相机权限");
            permissionList_camera.add(Manifest.permission.CAMERA);
            XXPermissionTool.checkPermissions(this, //
                    permissionList_camera, //
                    noteMap_camera, //
                    CODE_REQUEST_CAMERA_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                tempFile = ESystem.getPicturesCacheDir(PigaiStartActivity.this, ESystem.getCacheFileName("meinfo", "jpg"));
                                BaseJumpManager.jumpToSysCamera(PigaiStartActivity.this,
                                        tempFile, REQUEST_CODE_CAMERA);
                            }
                        }
                    });
        } else {
            tempFile = ESystem.getPicturesCacheDir(PigaiStartActivity.this, ViewUtil.getPhotoFileName());
            BaseJumpManager.jumpToSysCamera(PigaiStartActivity.this,
                    tempFile, REQUEST_CODE_CAMERA);
        }
    }

    private ALiYunManager.ALiYunListener listener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {

        }

        @Override
        public void onSuccess(Object tag, String url) {
            FileUtils.delete(String.valueOf(tag));
            hideMiddleProgressBar();
        }

        @Override
        public void onFailure(Object tag, int errorCode) {//要根据tag的值来判断  这个监听者是全局的 所以没有tag 我把提示删了
            hideMiddleProgressBar();
            //showToastError(R.string.upload_avatar_fail);
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_pigai_start;
    }

    @Override
    protected void findViews() {
        ll_take_phote_pigai = findViewById(R.id.ll_take_phote_pigai);
    }

    @Override
    protected void initEvent() {
        ll_take_phote_pigai.setOnClickListener(this);
        ALiYunManager.getInstance().registerListener(listener);
    }

    @Override
    protected void init() {
        setTitleText("作文");
        application = (EApplication) getApplication();
        setBottomMenuDialog();
        alertDialog = new AlertDialog.Builder(this);
        showRightBtn();
        setRightBtnText("识别记录");
        setRightBtnEnable(true);
        setRightBtnListener(new ViewOnClickListener() {
            @Override
            public void avertRepeatOnClick(View v) {
                PigaiJumpManager.jumpToEssayRecordListH5Activity(PigaiStartActivity.this, R.string.go_back, "");
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void loadData() {
        if (application != null) {
        }
    }


    private File cutImgFile;
    private File cutImgFileTemp;

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        if (resultCode == RESULT_OK) {
            Uri outPuturi;
            Intent intent = new Intent();
            switch (requestCode) {
                case REQUEST_CODE_CAMERA:
                    photoUri = FileProvider7.getUriForFile(this, tempFile);
                    cutImgFile = FileUtil.uriToPicturesFileApiQ(photoUri, PigaiStartActivity.this);
                    showGetPermissDialog();
                    break;
                case REQUEST_CODE_ALBUM:
                    if (data != null) {
                        photoUri = data.getData();
                        if (photoUri != null) {
                            cutImgFile = FileUtil.uriToPicturesFileApiQ(photoUri, PigaiStartActivity.this);
                            showGetPermissDialog();
                        }
                    }
                    break;
                case REQUEST_CODE_CROP_ALBUM:
                case REQUEST_CODE_CROP_CAMERA:
                    if (null != cutImgFileTemp) {
                        CWLog.i("byou", "cutImgFile.getPath()=" + cutImgFile.getPath());
                        if (Build.VERSION.SDK_INT >= 30) {
                            cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.getCropFile(getBaseContext(), com.ciwong.mobilelib.utils.FileUtil.uri);
                        }
                        if (checkTokenStatus()) {
                            if (!NetworkUtils.isOnline()) {
                                ToastUtil.INSTANCE.toastCenterNoNetError();
                            } else {
                                recWrittenText(PigaiStartActivity.this, cutImgFileTemp.getPath());
                            }
                        }
                    }
                    break;
                case CODE_REQUEST_ALBUM_PERMISSION:
                    if (XXPermissionTool.isHasPermission(PigaiStartActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        BaseJumpManager.jumpToSysAlbum(PigaiStartActivity.this,
                                REQUEST_CODE_ALBUM);
                    }
                    break;
                case CODE_REQUEST_CAMERA_PERMISSION:
                    if (XXPermissionTool.isHasPermission(PigaiStartActivity.this, Manifest.permission.CAMERA)) {
                        tempFile = ESystem.getPicturesCacheDir(PigaiStartActivity.this, ViewUtil.getPhotoFileName());
                        BaseJumpManager.jumpToSysCamera(PigaiStartActivity.this,
                                tempFile, REQUEST_CODE_CAMERA);
                    }
                    break;
                case REQUEST_CODE_WRITTEN_RESULT:
                    useCamera();
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_photo_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, getString(R.string.read_and_write_local_storage_permissions));
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                Uri outPuturi = Uri.fromFile(cutImgFile);
                                Uri imgUri = FileProvider7.getUriForFile(PigaiStartActivity.this, cutImgFile);

                                if (Build.VERSION.SDK_INT >= 30) {
                                    cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.createImageFile(getBaseContext(), true);
                                    //设置裁剪的图片地址Uri
                                    outPuturi = com.ciwong.mobilelib.utils.FileUtil.uri;
                                } else {
                                    cutImgFileTemp = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".png");
                                }
                                BaseJumpManager.jumpToSysCropPhotoPigai(PigaiStartActivity.this, imgUri, outPuturi, cutImgFileTemp,
                                        REQUEST_CODE_CROP_CAMERA, true);
                            } else {
//                                showConfirmCommitDialog(getActivity(), "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            Uri outPuturi = Uri.fromFile(cutImgFile);
            Uri imgUri = FileProvider7.getUriForFile(PigaiStartActivity.this, cutImgFile);
            if (Build.VERSION.SDK_INT >= 30) {
                cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.createImageFile(getBaseContext(), true);
                outPuturi = com.ciwong.mobilelib.utils.FileUtil.uri;
                //设置裁剪的图片地址Uri
            } else {

                cutImgFileTemp = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".png");
            }
            BaseJumpManager.jumpToSysCropPhoto(PigaiStartActivity.this, imgUri, outPuturi, cutImgFileTemp,
                    REQUEST_CODE_CROP_CAMERA, true, 200, 200);
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ALiYunManager.getInstance().unRegisterListener(listener);
        if (alertDialog != null) {
            alertDialog = null;
        }
    }

    // 使用系统当前日期加以调整作为照片的名称
    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    private void setBottomMenuDialog() {
        bottomMenuDialog = new BottomMenuDialog(this);
        bottomMenuDialog
                .setBtnTextColor(getResources().getColor(R.color.color_light_green));
        bottomMenuDialog
                .setLastBtnTextColor(getResources().getColor(R.color.gray));

        ArrayList<String> str = new ArrayList<>();

        str.add(getResources().getString(R.string.avatar_camera));
        str.add(getResources().getString(R.string.avatar_photo));
        str.add(getResources().getString(android.R.string.cancel));
        bottomMenuDialog.setMenuTextList(str);

        ArrayList<View.OnClickListener> listeners = new ArrayList<>();

        listeners.add(new BottomClickListener(0));
        listeners.add(new BottomClickListener(1));
        listeners.add(new BottomClickListener(2));

        bottomMenuDialog.setMenuOnClickListeners(listeners);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_take_phote_pigai) {
            bottomMenuDialog.show();
        } else if (id == R.id.my_info_avatar) {
        }
    }

    /**
     * 裁剪后的图片路径
     *
     * @param data
     * @return
     */
    public static String getCropPath(Intent data) {
        Bitmap bitmap = data.getParcelableExtra("data");
        if (bitmap != null) {
            FileOutputStream fos = null;
            File file = new File(ESystem.getUploadImgPath(),
                    getPhotoFileName());
            try {
                fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
            return file.getPath();
        }
        return "";
    }

    private boolean checkTokenStatus() {
        if (!application.isHasGotToken()) {
            Toast.makeText(getApplicationContext(), "识别系统还未成功初始化:" + application.getHasGotTokenMessage(), Toast.LENGTH_LONG).show();
        }
        return application.isHasGotToken();
    }

    public void recWrittenText(Context ctx, String filePath) {
        showCricleProgress("正在智能识别...");
        OcrRequestParams param = new OcrRequestParams();
        param.setImageFile(new File(filePath));
        OCR.getInstance(ctx).recoginzeWrittenText(param, new OnResultListener<OcrResponseResult>() {
            @Override
            public void onResult(OcrResponseResult result) {
                String rerult = result.getJsonRes();
                infoPopText(rerult);
            }

            @Override
            public void onError(OCRError error) {
                String errorrerult = error.getMessage();
                alertText("识别出错", errorrerult);
            }
        });
    }

    private void infoPopText(final String result) {
        String displyName = "";
        String relutName = "";
        try {
            JSONObject jsonObject = new JSONObject(result);
            JSONArray array = jsonObject.getJSONArray("words_result");
            for (int i = 0; i < array.length(); i++) {
                JSONObject jsonItem = array.getJSONObject(i);
                String word = jsonItem.getString("words");
                displyName = displyName + word + " \n ";
                relutName = relutName + word + " ";
            }
            hideCricleProgress();
            PigaiJumpManager.jumpToWrittenTextResult(R.string.go_back, PigaiStartActivity.this, relutName, REQUEST_CODE_WRITTEN_RESULT);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private AlertDialog.Builder alertDialog;

    private void alertText(final String title, final String message) {
        this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hideCricleProgress();
                if (alertDialog != null) {
                    alertDialog.setTitle(title)
                            .setMessage(message)
                            .setPositiveButton("确定", null)
                            .show();
                }
            }
        });
    }
}
